package com.timothy.android;

import com.timothy.question.STTwoButtonAlpha;
import com.timothy.service.MessageReceiveService;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends BaseActivity {
	private TextView console = null;
	
	private Button disConnectBtn = null;
	private Button offlineVoteBtn = null;
	
	private boolean mIsBound;
    
    private Messenger rMessenger = new Messenger( new IncomingHandler() );
    private Messenger sMessenger = null;
    
    //mock question button
    private Button question1Btn = null;
	private Button question2Btn = null;
    private Button question3Btn = null;
	private Button question4Btn = null;
    private Button question5Btn = null;
	private Button question6Btn = null;
	
    //mock answer button
    private Button answer1Btn = null;
	private Button answer2Btn = null;
    private Button answer3Btn = null;
	private Button answer4Btn = null;
    private Button answer5Btn = null;
	private Button answer6Btn = null;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		
		doBindService();
		
		Bundle bundle = this.getIntent().getExtras();
		String baseStationName = bundle.getString("baseStationName");
		if(baseStationName == null||"".equals(baseStationName)){
			baseStationName = "unknown";
		}
		
		//client component
		console = (TextView) this.findViewById(R.id.console);	
		console.setTextColor(Color.BLACK);
		console.setTextSize(15);
		console.setBackgroundColor(Color.parseColor("#ede26a"));
		
		console.append("Connected to BaseStation :" + baseStationName  + "\n");
		console.append("Waiting Server Send Question..." + "\n");
		console.append("If you want to enter offline vote, click button 'Offline Vote'" + "\n");
		
		initialMockButtons();
		
		initialMockAnswerButtons();
		
		disConnectBtn = (Button) this.findViewById(R.id.disConnectBtn);
		offlineVoteBtn = (Button) this.findViewById(R.id.offlineVoteBtn);
		
		//click end Button
		disConnectBtn.setOnClickListener( mUnbindListener );
		offlineVoteBtn.setOnClickListener( offlineVoteListener );
	}

	public void initialMockButtons(){
		
		
		question1Btn = (Button) this.findViewById(R.id.question1Btn);
		question1Btn.setText("True/False");
		question1Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutA.class);
			    bundle.putString("question", "IPhone is best smart phone?");
			    bundle.putString("choice1", "True");
			    bundle.putString("choice2", "False");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		question2Btn = (Button) this.findViewById(R.id.question2Btn);
		question2Btn.setText("Yes/No");
		question2Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutA.class);
			    bundle.putString("question", "Are you happy?");
			    bundle.putString("choice1", "Yes");
			    bundle.putString("choice2", "No");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		question3Btn = (Button) this.findViewById(R.id.question3Btn);
		question3Btn.setText("Yes/Abstain/No");
		question3Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutB.class);
			    bundle.putString("question", "Android is more popular than iPhone?");
			    bundle.putString("choice1", "Yes");
			    bundle.putString("choice2", "Abstain");
			    bundle.putString("choice3", "No");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		question4Btn = (Button) this.findViewById(R.id.question4Btn);
		question4Btn.setText("-/Neutral/+");
		question4Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutB.class);
			    bundle.putString("question", "Do you like play basketball?");
			    bundle.putString("choice1", "-");
			    bundle.putString("choice2", "Neutral");
			    bundle.putString("choice3", "+");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		question5Btn = (Button) this.findViewById(R.id.question5Btn);
		question5Btn.setText("Agree/Neutral/Disagree");
		question5Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutB.class);
			    bundle.putString("question", "Google is good company?");
			    bundle.putString("choice1", "Agree");
			    bundle.putString("choice2", "Neutral");
			    bundle.putString("choice3", "Disagree");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		question6Btn = (Button) this.findViewById(R.id.question6Btn);
		question6Btn.setText("Low/Med/High");
		question6Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, LayoutB.class);
			    bundle.putString("question", "What are your English Grade?");
			    bundle.putString("choice1", "Low");
			    bundle.putString("choice2", "Med");
			    bundle.putString("choice3", "High");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
	}
	
	public void initialMockAnswerButtons(){
		answer1Btn = (Button) this.findViewById(R.id.answer1Btn);
		answer1Btn.setText("True/False");
		answer1Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "IPhone is best smart phone?");
			    bundle.putString("vote1", "50");
			    bundle.putString("vote2", "50");
			    bundle.putString("choice1", "True");
			    bundle.putString("choice2", "False");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		answer2Btn = (Button) this.findViewById(R.id.answer2Btn);
		answer2Btn.setText("Yes/No");
		answer2Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "Are you happy?");
			    bundle.putString("vote1", "70");
			    bundle.putString("vote2", "30");
			    bundle.putString("choice1", "Yes");
			    bundle.putString("choice2", "No");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		answer3Btn = (Button) this.findViewById(R.id.answer3Btn);
		answer3Btn.setText("Yes/Abstain/No");
		answer3Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "Android is more popular than iPhone?");
			    bundle.putString("choice1", "Yes");
			    bundle.putString("choice2", "Abstain");
			    bundle.putString("choice3", "No");
			    bundle.putString("vote1", "10");
			    bundle.putString("vote2", "20");
			    bundle.putString("vote3", "70");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		answer4Btn = (Button) this.findViewById(R.id.answer4Btn);
		answer4Btn.setText("-/Neutral/+");
		answer4Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "Do you like play basketball?");
			    bundle.putString("choice1", "-");
			    bundle.putString("choice2", "Neutral");
			    bundle.putString("choice3", "+");
			    bundle.putString("vote1", "40");
			    bundle.putString("vote2", "40");
			    bundle.putString("vote3", "20");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		answer5Btn = (Button) this.findViewById(R.id.answer5Btn);
		answer5Btn.setText("Agree/Neutral/Disagree");
		answer5Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "Google is good company?");
			    bundle.putString("choice1", "Agree");
			    bundle.putString("choice2", "Neutral");
			    bundle.putString("choice3", "Disagree");
			    bundle.putString("vote1", "10");
			    bundle.putString("vote2", "30");
			    bundle.putString("vote3", "60");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
		
		answer6Btn = (Button) this.findViewById(R.id.answer6Btn);
		answer6Btn.setText("Low/Med/High");
		answer6Btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				Intent intent = new Intent();
			    intent.setClass(HomeActivity.this, Bar2DAnswerActivity.class);
			    bundle.putString("questionName", "What are your English Grade?");
			    bundle.putString("choice1", "Low");
			    bundle.putString("choice2", "Med");
			    bundle.putString("choice3", "High");
			    bundle.putString("vote1", "20");
			    bundle.putString("vote2", "30");
			    bundle.putString("vote3", "50");
			    intent.putExtras(bundle);
			    startActivity(intent);	
			}
		});
	}
	
    private ServiceConnection mrsConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 sMessenger = new Messenger( service );
             // We want to monitor the service for as long as we are connected to it.
             try {
                 Message msg = Message.obtain(null, MessageReceiveService.MSG_REGISTER_CLIENT);
                 msg.replyTo = rMessenger;
                 sMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
        
            mIsBound = true;
            // Tell the user about this for our demo.
            Toast.makeText(HomeActivity.this, R.string.message_receive_service_connected, Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
        	 Message msg = Message.obtain(null, MessageReceiveService.MSG_UNREGISTER_CLIENT);
             msg.replyTo = rMessenger;
             try {
            	 sMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
            Toast.makeText(HomeActivity.this, R.string.message_receive_service_disconnected, Toast.LENGTH_SHORT).show();
        }
    };

    void doBindService() {
        // Establish a connection with the service.  We use an explicit
        // class name because we want a specific service implementation that
        // we know will be running in our own process (and thus won't be
        // supporting component replacement by other applications).
        bindService(new Intent(HomeActivity.this, MessageReceiveService.class), mrsConnection, Context.BIND_AUTO_CREATE);
    }

    void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            unbindService(mrsConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            doUnbindService();
        }
    };    

    private OnClickListener offlineVoteListener = new OnClickListener() {
        public void onClick(View v) {
        	
        }
    };


	class IncomingHandler extends Handler {
	        @Override
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	                case MessageReceiveService.MSG_QUESTION:
//                		Object obj = null;
//        			    String type = XMLUtil.getPropertyValue(msg.obj.toString(), "Type");
//        				if( "CommonQuestion".equals( type ) ) {
//        					int index = msg.obj.toString().indexOf("<Content>")+"<Content>".length();
//        					int endIndex = msg.obj.toString().indexOf("</Content>");
//        					String question = msg.obj.toString().substring(index, endIndex);
//        					obj = QuestionBuilder.parseQuestion( question );
//        				}
        				
	                	if(msg.obj instanceof STTwoButtonAlpha ) {
//	                		console.setText( msg.obj.toString() +"dddddddddddd" );
	                		//TODO... launch activity here;
	                		STTwoButtonAlpha st = (STTwoButtonAlpha) msg.obj;
	                		Log.i("message", msg.obj.toString());
	        				Intent intent = new Intent();
	        				intent.putExtra("STTwoButtonAlpha", st.getXmlString());
	        			    intent.setClass(HomeActivity.this,LayoutA.class);
	        			    startActivity(intent);
	                	}
	                	
	                    break;
	                default:
	                    super.handleMessage(msg);
	            }
	        }
	  }
		 

}
